package com.lin.fragments;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.sidingbar2.view.MySideBar;
import com.sidingbar2.view.MySideBar.OnTouchingLetterChangedListener;
import com.sidingbar2.view.PinyinUtils;
import com.t9search.util.PinyinUtil;
import com.lin.activity.AddFriendActivity;
import com.lin.activity.MyFensiListActivity;
import com.lin.activity.MyFocusListActivity;
import com.lin.activity.MyFriendsApplicationListActivity;
import com.lin.activity.PersonalDetailCardActivity;
import com.lin.activity.PersonalDetailCardInPhoneActivity;
import com.lin.activity.TestDatabasePOIActivity2;
import com.lin.fragments.RecentCallFragment.UpdateBroadcastReceiver2;
import com.lin.utils.DatabaseHelperForChattingMap;
import com.lin.utils.Parameters;
import com.lin.utils.Session;
import com.lin.utils.Utils;
import com.lin.utils.Session.SignupResult;
import com.lin.views.CustomPopupWindow;
import com.lin.views.ListViewForContactsInPhone;
import com.lin.views.ListViewForSuperFriends;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.activity.BaseActivity;
import com.yunfeng.supercall.activity.ChatActivity;
import com.yunfeng.supercall.activity.EnterPriseFriendsActivity;
import com.yunfeng.supercall.activity.FriendsGroupListActivity;
import com.yunfeng.supercall.activity.MyCircleListActivity;
import com.yunfeng.supercall.activity.NewSuperFriendsListActivity;
import com.yunfeng.supercall.bean.Constants;
import com.yunfeng.supercall.bean.FriendsShareBean;
import com.yunfeng.supercall.bean.PhoneContactsBean;
import com.yunfeng.supercall.bean.SuperFriendsBean;
import com.yunfeng.supercall.bean.UserBean;
import com.yunfeng.supercall.manager.SuperFriendsManager;
import android.provider.ContactsContract.Groups;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.lin.utils.Session.ResultReceiver;

public class SuperFriendsFragment extends Fragment implements
OnTouchingLetterChangedListener, OnItemClickListener, Constants,
OnClickListener {
	View mView;
	ListViewForSuperFriends mListview;
	Session mSession;
	private MySideBar sideBar;
	ArrayList<SuperFriendsBean> mArrayListSuperFriendsdBean;
	private ImageView mImageView1;
	private ImageView mImageView2;
	private Button mButton1;
	private Button mButton2;
	private ArrayList<PhoneContactsBean> mPhoneContacts;
	private ListViewForContactsInPhone mListviewInPhone;
	TextView mTextView1;
	TextView mTextView2;
	boolean state = false;
	UserBean mUserBean;
	CustomPopupWindow pw;
	private View frameLayoutSearch;
	UpdateBroadcastReceiver2 mUpdateBroadcastReceiver2;

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		// mView = inflater.inflate(R.layout.fragment_superfriends, null);

		Log.i("TAG", "onCreateView");

		if (mView == null) {
			mView = inflater.inflate(R.layout.fragment_superfriends, null);
		}
		// 缓存的rootView需要判断是否已经被加过parent，如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
		ViewGroup parent = (ViewGroup) mView.getParent();
		if (parent != null) {
			parent.removeView(mView);
		}
		mUserBean = BaseActivity.getUser(getActivity());
		frameLayoutSearch = mView.findViewById(R.id.framelayout_search);
		mEditTextSearch = (EditText) mView.findViewById(R.id.et_search);


		pw = new CustomPopupWindow(getActivity());
		FrameLayout mFrameLayoutMore = (FrameLayout) mView
				.findViewById(R.id.framelayout_more);
		mFrameLayoutMore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pw.show();
			}
		});

		mSession = Session.getSession();
		mSession.init(getActivity(), true);

		mUserBean = mSession.getmUserBean();
		// mUserBean = BaseActivity.getUser(getActivity());

		sideBar = (MySideBar) mView.findViewById(R.id.myView);
		mListview = (ListViewForSuperFriends) mView.findViewById(R.id.listview);
		//mListview.addHeaderView(getActivity().getLayoutInflater().inflate(R.layout.list_header_search, null));
		mListviewInPhone = (ListViewForContactsInPhone) mView
				.findViewById(R.id.listview_in_phone);

		mTextView1 = (TextView) mView.findViewById(R.id.textView1);
		mTextView2 = (TextView) mView.findViewById(R.id.textView2);
		mImageView1 = (ImageView) mView.findViewById(R.id.imageview1);
		mImageView2 = (ImageView) mView.findViewById(R.id.imageview2);

		mButton1 = (Button) mView.findViewById(R.id.button1);
		mButton2 = (Button) mView.findViewById(R.id.button2);
		mListview.setDataList(new ArrayList<SuperFriendsBean>());

		mButton2.setOnClickListener(this);
		mButton1.setOnClickListener(this);
		sideBar.setOnTouchingLetterChangedListener(this);
		mListview.setOnItemClickListener(this);

		frameLayoutSearch.setOnClickListener(this);

		mListviewInPhone.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getActivity(),
						PersonalDetailCardInPhoneActivity.class);
				intent.putExtra("data", mPhoneContacts.get(arg2));

				startActivity(intent);

			}
		});

		IntentFilter filter = new IntentFilter();
		filter.addAction(ACTION_NEWFRIEND_MSG);
		mUpdateBroadcastReceiver = new UpdateBroadcastReceiver();
		getActivity().registerReceiver(mUpdateBroadcastReceiver, filter);

		mSwipeRefreshLayout = (SwipeRefreshLayout) mView
				.findViewById(R.id.swipe);

		mSwipeRefreshLayout.setColorSchemeResources(R.color.base_orange);
		mSwipeRefreshLayout.setRefreshing(true);
		mSwipeRefreshLayout.setEnabled(false);

		mListview.setOnScrollListener(new AbsListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView absListView, int i) {

			}

			@Override
			public void onScroll(AbsListView absListView, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				mSwipeRefreshLayout.setEnabled(false);
				if (firstVisibleItem == 0)
					mSwipeRefreshLayout.setEnabled(true);
				else
					mSwipeRefreshLayout.setEnabled(false);
			}
		});

		mSwipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				String stringET = mEditTextSearch.getText().toString();
				if(TextUtils.isEmpty(stringET)) {
					mSwipeRefreshLayout.setRefreshing(true);
					load();
				} else {
					mSwipeRefreshLayout.setRefreshing(false);
				}
			}
		});

		load();
		/*
		 * mSession.getFriendList(getActivity(),mUserBean.getUserid(), 0, new
		 * ResultReceiver<ArrayList<SuperFriendsBean>>(){
		 * 
		 * @Override public void onResult(boolean last,
		 * ArrayList<SuperFriendsBean> data) { // TODO Auto-generated method
		 * stub int position = 0; mArrayList = new
		 * ArrayList<SuperFriendsBean>(); for(Iterator<SuperFriendsBean>
		 * iterator= data.iterator();iterator.hasNext();) { SuperFriendsBean
		 * mBean = iterator.next(); if(mBean.getType() != 2) {
		 * mArrayList.add(mBean); } }
		 * 
		 * DatabaseHelperForChattingMap dbHelper3 = new
		 * DatabaseHelperForChattingMap(getActivity(), "db", 2);
		 * dbHelper3.insertSuperFrined(data); if(dbHelper3 != null) {
		 * dbHelper3.close(); dbHelper3 = null; } for(Iterator<SuperFriendsBean>
		 * iterator=data.iterator();iterator.hasNext();) { SuperFriendsBean
		 * mBean = iterator.next(); }
		 * 
		 * // String nickName; // String pingyin = ""; // String firstSpell =
		 * "#"; // SuperFriendsBean superFriendBean = new SuperFriendsBean(); //
		 * superFriendBean.setNick_name(firstSpell); // data.add(position,
		 * superFriendBean); // int size = data.size(); // position ++ ; //
		 * while(position < size) { // SuperFriendsBean superFriendsBean =
		 * data.get(position); // nickName = superFriendsBean.getNick_name(); //
		 * if(nickName != null) { // pingyin =
		 * PinyinUtils.converterToFirstSpell(nickName); // } // String
		 * secondTime = new String(pingyin.substring(0, 1)).trim(); // String
		 * firstTime = new String(firstSpell.trim()); // Character firstChar =
		 * firstTime.charAt(0) ; // Character secondChar = secondTime.charAt(0)
		 * ; // // if(firstChar.compareTo(secondChar) != 0) // firstSpell =
		 * secondTime; // if (pingyin.length() > 0) { // superFriendBean = new
		 * SuperFriendsBean(); //
		 * superFriendBean.setNick_name(pingyin.substring(0, 1)); //
		 * data.add(position, superFriendBean); // size = data.size(); //
		 * position ++ ; // } // position ++ ; // } if(data != null) {
		 * mListview.setDataList(mArrayList); }
		 * 
		 * }
		 * 
		 * });
		 */

		IntentFilter filter2 = new IntentFilter();
		filter2.addAction(ACTION_UPDATE_PHONE);
		mUpdateBroadcastReceiver2 = new UpdateBroadcastReceiver2();
		getActivity().registerReceiver(mUpdateBroadcastReceiver2, filter2);


		mEditTextSearch.addTextChangedListener(textWatcher);
		return mView;
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		if (mUpdateBroadcastReceiver2 != null) {
			getActivity().unregisterReceiver(mUpdateBroadcastReceiver2);
			mUpdateBroadcastReceiver2 = null;
		}
	}

	private void load() {
		mSession.getNoGroupFriendList(getActivity(), 0,
				new ResultReceiver<ArrayList<SuperFriendsBean>>() {

			@Override
			public void onResult(boolean last,
					ArrayList<SuperFriendsBean> data) {
				// TODO Auto-generated method stub
				mSwipeRefreshLayout.setRefreshing(false);

				if (data != null) {
					int position = 0;
					mArrayListSuperFriendsdBean = new ArrayList<SuperFriendsBean>();
					for (Iterator<SuperFriendsBean> iterator = data
							.iterator(); iterator.hasNext();) {
						SuperFriendsBean mBean = iterator.next();
						if (mBean.getType() != 2) {
							mArrayListSuperFriendsdBean.add(mBean);
						}
					}

					DatabaseHelperForChattingMap dbHelper3 = new DatabaseHelperForChattingMap(
							getActivity(), "db", 2);
					dbHelper3.insertSuperFrined(data);
					dbHelper3.insertSuperFriendsUserInfo(data);
					if (dbHelper3 != null) {
						dbHelper3.close();
						dbHelper3 = null;
					}

					for (Iterator<SuperFriendsBean> iterator = data
							.iterator(); iterator.hasNext();) {
						SuperFriendsBean mBean = iterator.next();
					}

					// String nickName;
					// String pingyin = "";
					// String firstSpell = "#";
					// SuperFriendsBean superFriendBean = new
					// SuperFriendsBean();
					// superFriendBean.setNick_name(firstSpell);
					// data.add(position, superFriendBean);
					// int size = data.size();
					// position ++ ;
					// while(position < size) {
					// SuperFriendsBean superFriendsBean =
					// data.get(position);
					// nickName = superFriendsBean.getNick_name();
					// if(nickName != null) {
					// pingyin =
					// PinyinUtils.converterToFirstSpell(nickName);
					// }
					// String secondTime = new
					// String(pingyin.substring(0, 1)).trim();
					// String firstTime = new String(firstSpell.trim());
					// Character firstChar = firstTime.charAt(0) ;
					// Character secondChar = secondTime.charAt(0) ;
					//
					// if(firstChar.compareTo(secondChar) != 0)
					// firstSpell = secondTime;
					// if (pingyin.length() > 0) {
					// superFriendBean = new SuperFriendsBean();
					// superFriendBean.setNick_name(pingyin.substring(0,
					// 1));
					// data.add(position, superFriendBean);
					// size = data.size();
					// position ++ ;
					// }
					// position ++ ;
					// }
					if (data != null) {
						mListview.setDataList(mArrayListSuperFriendsdBean);
					}
				} else { // 没有网络
					DatabaseHelperForChattingMap mDatabaseHelperForChattingMap = new DatabaseHelperForChattingMap(
							getActivity(), "db", 2);
					mArrayListSuperFriendsdBean = mDatabaseHelperForChattingMap
							.getFriendsUserInfoList();
					mListview.setDataList(mArrayListSuperFriendsdBean);
				}
			}

		});
		mListview.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				Utils.hidenKeyBoard(getActivity(), mEditTextSearch);
				return false;
			}
		});

		mListviewInPhone.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				Utils.hidenKeyBoard(getActivity(), mEditTextSearch);
				return false;
			}
		});
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (mUpdateBroadcastReceiver != null) {
			getActivity().unregisterReceiver(mUpdateBroadcastReceiver);
			mUpdateBroadcastReceiver = null;
		}
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

	}

	@Override
	public void onTouchingLetterChanged(String s) {
		// TODO Auto-generated method stub
		try {
			if (state == false) {

				int position = alphaIndexer(s);
				if (position > 0) {
					mListview.setSelection(position);
				}
			} else {

				int position = alphaIndexerInPhone(s);
				if (position > 0) {
					mListviewInPhone.setSelection(position);
				}
			}
		} catch (NullPointerException e) {

		}
	}

	public int alphaIndexer(String s) {
		int position = 0;
		for (int i = 0; i < mArrayListSuperFriendsdBean.size(); i++) {
			com.sidingbar2.view.PinyinUtils.getAlpha("唐僧");
			if (PinyinUtils.getAlpha(mArrayListSuperFriendsdBean.get(i).getNick_name())
					.startsWith(s)) {
				position = i;
				break;
			}
		}
		return position;
	}

	public int alphaIndexerInPhone(String s) {
		int position = 0;
		for (int i = 0; i < mArrayListSuperFriendsdBean.size(); i++) {
			com.sidingbar2.view.PinyinUtils.getAlpha("唐僧");
			if (PinyinUtils.getAlpha(mArrayListSuperFriendsdBean.get(i).getNick_name())
					.startsWith(s)) {
				position = i;
				break;
			}
		}
		return position;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		if (position == 0) {
			SuperFriendsManager.setHasNewFriend(getActivity(), false);
			mListviewInPhone.updateDate();
			// startActivityForResult(new Intent(getActivity(),
			// NewSuperFriendsListActivity.class), 1);
			mListview.setDataList(mArrayListSuperFriendsdBean);
			SuperFriendsManager.setHasNewFriend(getActivity(), false);
			startActivity(new Intent(getActivity(),
					NewSuperFriendsListActivity.class));
		} else if (position == 1) {
			/*
			 * startActivity(new Intent(getActivity(),
			 * MyFriendsApplicationListActivity.class));
			 */
			startActivity(new Intent(getActivity(),
					EnterPriseFriendsActivity.class));
		} else if (position == 2) {
			startActivity(new Intent(getActivity(), MyFocusListActivity.class)
			.putExtra("data", mUserBean.getUserid()));
		} else if (position == 3) {
			startActivity(new Intent(getActivity(), MyFensiListActivity.class)
			.putExtra("data", mUserBean.getUserid()));
		} else if (position != mListview.getAdapter().getCount() - 1){
			/*
			 * startActivity(new Intent(getActivity(), ChatActivity.class)
			 * .putExtra(KEY_DATA, mArrayList.get(position-4)));
			 */
			startActivity(new Intent(getActivity(),
					PersonalDetailCardActivity.class).putExtra("data",
							mArrayListSuperFriendsdBean.get(position - 4)));
		}
	}

	/**
	 * 为了得到传回的数据，必须在前面的Activity中（指MainActivity类）重写onActivityResult方法
	 * 
	 * requestCode 请求码，即调用startActivityForResult()传递过去的值 resultCode
	 * 结果码，结果码用于标识返回数据来自哪个新Activity
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		String result = data.getExtras().getString("result");// 得到新Activity
		// 关闭后返回的数据
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == mButton1) {
			state = false;
			mListview.setVisibility(View.VISIBLE);
			mListviewInPhone.setVisibility(View.INVISIBLE);
			mImageView1.setVisibility(View.VISIBLE);
			mImageView2.setVisibility(View.INVISIBLE);
			mTextView1.setTextColor(getResources()
					.getColor(R.color.base_orange));
			mTextView2.setTextColor(getResources().getColor(R.color.white));
			mSwipeRefreshLayout.setVisibility(View.VISIBLE);
		} else if (v == mButton2) {
			state = true;
			mListview.setVisibility(View.INVISIBLE);
			mListviewInPhone.setVisibility(View.VISIBLE);
			mImageView1.setVisibility(View.INVISIBLE);
			mImageView2.setVisibility(View.VISIBLE);
			mTextView2.setTextColor(getResources()
					.getColor(R.color.base_orange));
			mTextView1.setTextColor(getResources().getColor(R.color.white));

			mSwipeRefreshLayout.setVisibility(View.GONE);
		} else if (v == frameLayoutSearch) {
			startActivity(new Intent(getActivity(), AddFriendActivity.class));
			// boolean has = SuperFriendsManager.hasNewFriend(getActivity());

			// viewholder.red_dot.setVisibility(has ? View.VISIBLE :
			// View.INVISIBLE);
		}
	}

	Runnable runnable = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			// mPhoneContacts = getAllGroupInfo();
			// mPhoneContacts = getPeopleInPhone2();

			mPhoneContacts = Parameters.mArrayListPhoneContactsBean;

			mHandler.sendEmptyMessage(0);

		}

	};

	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if (mPhoneContacts != null)
				mListviewInPhone.setDataList(mPhoneContacts);
		}

	};
	private String strContactId;

	private ArrayList<PhoneContactsBean> getPeopleInPhone2() {
		ArrayList<PhoneContactsBean> list = new ArrayList<PhoneContactsBean>();
		try {
			int cpt = 0;
			Cursor cursor = getActivity().getContentResolver().query(
					ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
					null, null, null); // 获取手机联系人
			while (cursor.moveToNext()) {

				int indexPeopleName = cursor.getColumnIndex(Phone.DISPLAY_NAME); // people
				// name
				int indexPhoneNum = cursor.getColumnIndex(Phone.NUMBER); // phone
				int indexphotouri = cursor
						.getColumnIndex(Phone.PHOTO_THUMBNAIL_URI); // phone
				// number
				int indexID = cursor.getColumnIndex(Phone.CONTACT_ID); // phone
				String strPeopleName = cursor.getString(indexPeopleName);
				String strPhoneNum = cursor.getString(indexPhoneNum);
				String strPhotoUri = cursor.getString(indexphotouri);
				strContactId = cursor.getString(indexID);
				PhoneContactsBean map = new PhoneContactsBean();
				// 遍历是否是超友
				try {

					isSuperUser(strPhoneNum, map);
				} catch (NullPointerException e) {

				}
				map.setPhoto(strPhotoUri);
				map.setNick_name(strPeopleName);
				map.setPhone(strPhoneNum);
				map.setGroup("未分组");
				// PinyinUtil.chineseStringToPinyinUnit(map.getNick_name(),
				// map.getNamePinyinUnits());

				// 默认查询全部的分组
				/*
				 * cursor =
				 * getActivity().getContentResolver().query(ContactsContract
				 * .Data.CONTENT_URI, null, "raw_contact_id=?", new String[]
				 * {strContactId}, null); while (cursor.moveToNext()) { String
				 * name =
				 * cursor.getString(cursor.getColumnIndex(ContactsContract
				 * .CommonDataKinds.GroupMembership.DISPLAY_NAME));
				 * map.setGroup(name); long id =
				 * cursor.getLong(cursor.getColumnIndex(Groups._ID)); }
				 */

				// map.setPhone(strPhoneNum);
				map.setContactsFromPhone(true);
				list.add(map);
				cpt++;
			}
			if (!cursor.isClosed()) {
				cursor.close();
				cursor = null;
			}
			Collections.sort(list);
			mPhoneContacts = list;
		} catch (NullPointerException e) {

		}

		return list;
	}

	private void isSuperUser(String strPhoneNum, PhoneContactsBean map) {
		for (Iterator<SuperFriendsBean> interator = mArrayListSuperFriendsdBean.iterator(); interator
				.hasNext();) {
			SuperFriendsBean mSuperFriendBean = interator.next();
			if (mSuperFriendBean.getPhone().trim().equals(strPhoneNum)) {
				map.setSuper(true);
			}
		}
	}

	public boolean fetchContacts() {

		String phoneNumber = null;
		String email = null;
		String group = null;
		int i = 0;
		Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
		String _ID = ContactsContract.Contacts._ID;
		String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
		String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;

		Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
		String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
		String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;

		Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
		String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
		String DATA = ContactsContract.CommonDataKinds.Email.DATA;

		ContentResolver contentResolver = getActivity().getContentResolver();

		Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null,
				null);

		// Loop for every contact in the phone
		if (cursor.getCount() > 0) {

			while (cursor.moveToNext()) {
				String contact_id = cursor
						.getString(cursor.getColumnIndex(_ID));
				String name = cursor.getString(cursor
						.getColumnIndex(DISPLAY_NAME));

				int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor
						.getColumnIndex(HAS_PHONE_NUMBER)));

				if (hasPhoneNumber > 0) {

					// Query and loop for every phone number of the contact
					Cursor phoneCursor = contentResolver.query(
							PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?",
							new String[] { contact_id }, null);

					while (phoneCursor.moveToNext()) {
						phoneNumber = phoneCursor.getString(phoneCursor
								.getColumnIndex(NUMBER));
					}

					phoneCursor.close();

					// Query and loop for every email of the contact
					Cursor emailCursor = contentResolver.query(
							EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?",
							new String[] { contact_id }, null);

					while (emailCursor.moveToNext()) {
						email = emailCursor.getString(emailCursor
								.getColumnIndex(DATA));
					}

					emailCursor.close();

				}

				i++;
			}

		}

		return true;
	}

	/**
	 * 获取所有的 联系人分组信息
	 * 
	 * @return
	 */
	public ArrayList<PhoneContactsBean> getAllGroupInfo() {

		ArrayList<PhoneContactsBean> groupList = new ArrayList<PhoneContactsBean>();

		Cursor cursor = null;

		try {
			cursor = getActivity().getContentResolver().query(
					Groups.CONTENT_URI, null, null, null, null);

			while (cursor.moveToNext()) {

				int groupId = cursor.getInt(cursor.getColumnIndex(Groups._ID)); // 组id
				String groupName = cursor.getString(cursor
						.getColumnIndex(Groups.TITLE)); // 组名

				Log.i("MainActivity", "group id:" + groupId + ">>groupName:"
						+ groupName);

				String[] RAW_PROJECTION = new String[] { ContactsContract.Data.RAW_CONTACT_ID, };

				String RAW_CONTACTS_WHERE = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID
						+ "=?"
						+ " and "
						+ ContactsContract.Data.MIMETYPE
						+ "="
						+ "'"
						+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE
						+ "'";

				// 通过分组的id 查询得到RAW_CONTACT_ID
				Cursor cursor2 = getActivity().getContentResolver().query(
						ContactsContract.Data.CONTENT_URI, RAW_PROJECTION,
						RAW_CONTACTS_WHERE, new String[] { groupId + "" },
						"data1 asc");

				while (cursor2.moveToNext()) {
					PhoneContactsBean ge = new PhoneContactsBean();
					// RAW_CONTACT_ID
					int col = cursor2.getColumnIndex("raw_contact_id");
					int raw_contact_id = cursor2.getInt(col);

					// Log.i("getAllContactsByGroupId", "raw_contact_id:" +
					// raw_contact_id);

					// ce.setContactId(raw_contact_id);

					Uri dataUri = Uri
							.parse("content://com.android.contacts/data");
					Cursor dataCursor = getActivity().getContentResolver()
							.query(dataUri, null, "raw_contact_id=?",
									new String[] { raw_contact_id + "" }, null);

					while (dataCursor.moveToNext()) {
						String data1 = dataCursor.getString(dataCursor
								.getColumnIndex("data1"));
						String mime = dataCursor.getString(dataCursor
								.getColumnIndex("mimetype"));

						if ("vnd.android.cursor.item/phone_v2".equals(mime)) {
							ge.setPhone(data1);
							// ce.setTelNumber(data1);
						} else if ("vnd.android.cursor.item/name".equals(mime)) {
							ge.setNick_name(data1);
							// ce.setContactName(data1);
						}
						ge.setGroup(groupName);
						groupList.add(ge);
					}

					dataCursor.close();
				}

				cursor2.close();

			}
			cursor.close();
			Collections.sort(groupList);
			return groupList;

		} finally {
			if (cursor != null) {
				cursor.close();
			}
		}
	}

	/**
	 * 获取某个分组下的 所有联系人信息 思路：通过组的id 去查询 RAW_CONTACT_ID, 通过RAW_CONTACT_ID去查询联系人
	 * 要查询得到 data表的Data.RAW_CONTACT_ID字段
	 * 
	 * @param groupId
	 * @return
	 */
	/*
	 * public List<ContactEntity> getAllContactsByGroupId(int groupId) {
	 * 
	 * 
	 * 
	 * return contactList; }
	 */
	private UpdateBroadcastReceiver mUpdateBroadcastReceiver;
	private SwipeRefreshLayout mSwipeRefreshLayout;

	class UpdateBroadcastReceiver extends BroadcastReceiver {

		public UpdateBroadcastReceiver() {

		}

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			Log.i("jpsuh", "update data");
			load();
			// mListview.setDataList(mArrayList);
		}

	}

	class UpdateBroadcastReceiver2 extends BroadcastReceiver {

		public UpdateBroadcastReceiver2() {

		}

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (Parameters.mArrayListPhoneContactsBean != null) {
				new Thread(runnable).start();
			}
		}

	}
	private TextWatcher textWatcher = new TextWatcher() {  

		@Override    
		public void afterTextChanged(Editable s) {     
			// TODO Auto-generated method stub
			try {

				if(mListview.getVisibility() == View.VISIBLE) {
					String res = s.toString();
					if(TextUtils.isEmpty(res)) {
						mListview.setDataList(mArrayListSuperFriendsdBean);
						return;
					}
					Pattern p = Pattern.compile(res, Pattern.CASE_INSENSITIVE); 
					ArrayList<SuperFriendsBean> newFriendsShareBeanList = new ArrayList<SuperFriendsBean>();
					boolean isAdded = false;
					for(Iterator<SuperFriendsBean> iterator=mArrayListSuperFriendsdBean.iterator();iterator.hasNext();) {
						isAdded = false;
						SuperFriendsBean mBean = iterator.next();
						Matcher m = p.matcher(mBean.getNick_name());
						if(m.find()) {
							mBean.setPositionNickNameStart(m.start());
							mBean.setPositionNickNameEnd(m.end());
							isAdded = true;
						}
						if(isAdded == true) {
							newFriendsShareBeanList.add(mBean);
						}

					}

					mListview.setDataList(newFriendsShareBeanList);
				} else {

					String res = s.toString();
					if(TextUtils.isEmpty(res)) {
						mListview.setDataList(mArrayListSuperFriendsdBean);
						return;
					}
					Pattern p = Pattern.compile(res, Pattern.CASE_INSENSITIVE); 
					ArrayList<PhoneContactsBean> newFriendsShareBeanList = new ArrayList<PhoneContactsBean>();
					boolean isAdded = false;
					for(Iterator<PhoneContactsBean> iterator=mPhoneContacts.iterator();iterator.hasNext();) {
						isAdded = false;
						PhoneContactsBean mBean = iterator.next();
						Matcher m = p.matcher(mBean.getNick_name());
						if(m.find()) {
							mBean.setPositionNickNameStart(m.start());
							mBean.setPositionNickNameEnd(m.end());
							isAdded = true;
						}
						if(isAdded == true) {
							newFriendsShareBeanList.add(mBean);
						}

					}

					mListviewInPhone.setDataList(newFriendsShareBeanList);
				}
				Log.d("TAG","afterTextChanged--------------->");
			} catch(NullPointerException e) {

			}
		}   

		@Override 
		public void beforeTextChanged(CharSequence s, int start, int count,  
				int after) {  
			// TODO Auto-generated method stub  
			Log.d("TAG","beforeTextChanged--------------->");  
		}  

		@Override    
		public void onTextChanged(CharSequence s, int start, int before,     
				int count) {     
			Log.d("TAG","onTextChanged--------------->");    

		}                    
	};
	private EditText mEditTextSearch;  
}
